#!/usr/bin/python
# -*- coding: gb2312 -*-

import cookielib
import urllib2
import com.mitbbs.util.system as sys

if __name__ == '__main__':
    pass

class Firefox():
    def __init__(self):
        self.cookie_jar = self.sqlite2cookie(sys.get_system().cookies_sqlite_path())
    
    def sqlite2cookie(self, filename):
        from cStringIO import StringIO
        from sqlite3 import dbapi2 as sqlite
    
        con = sqlite.connect(filename)
    
        cur = con.cursor()
        cur.execute("select host, path, isSecure, expiry, name, value from moz_cookies")
    
        ftstr = ["FALSE","TRUE"]
    
        s = StringIO()
        header = "# Netscape HTTP Cookie File" +\
                 "# http://www.netscape.com/newsref/std/cookie_spec.html" +\
                 "# This is a generated file!  Do not edit."
        s.write(header)
        for item in cur.fetchall():
            s.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (item[0], ftstr[item[0].startswith('.')], item[1], ftstr[item[2]], item[3], item[4], item[5]))
    
        s.seek(0)
    
        cookie_jar = cookielib.MozillaCookieJar()
        cookie_jar._really_load(s, '', True, True)
        return cookie_jar

    def set_cookie(self, name, value, domain='.mitbbs.com'):
        cookie = cookielib.Cookie(version=0, 
                                  name=name, 
                                  value=value, 
                                  port=None,
                                  port_specified=False, 
                                  domain='.mitbbs.com',
                                  domain_specified=False, 
                                  domain_initial_dot=False, 
                                  path='/',
                                  path_specified=True, 
                                  secure=False, 
                                  expires=None,
                                  discard=True, 
                                  comment=None, 
                                  comment_url=None,
                                  rest={'HttpOnly': None}, 
                                  rfc2109=False)
        self.cookie_jar.set_cookie(cookie)
        
    def open_url(self, url, data=None):
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
        if data:
            r = opener.open(url, data)
        else:
            r = opener.open(url)
        return r.read()       #.decode('gb2312')
    
    def print_cookie(self, domain='.mitbbs.com'):
        for cookie in self.cookie_jar:
            if cookie.domain == domain:
                print cookie
